import requests
import time
from PIL import Image
import pytesseract
from utils.request_utils import get_random_user_agent
import random

# 指定 Tesseract OCR 引擎的安装路径
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

# 代理 IP 获取 API
PROXY_API_URL = "http://bapi.51daili.com/getapi2?linePoolIndex=-1&packid=2&time=32&qty=1&port=1&format=txt&ct=1&usertype=17&uid=58347&accessName=aa443717036&accessPassword=A95E5439EBA40E2DCC8744DA805E4E21&skey=autoaddwhiteip"

class UserAuthentication:
    def __init__(self):
        self.session = requests.Session()
        self.login_status = False
        self.login_time = None

    def get_proxy(self):
        try:
            response = requests.get(PROXY_API_URL)
            if response.status_code == 200:
                proxy_ip = response.text.strip()
                print(f"获取到的代理 IP: {proxy_ip}")  # 添加调试信息
                # 修改代理配置，将 https 也设置为 http
                return {"http": f"http://{proxy_ip}", "https": f"http://{proxy_ip}"}
        except Exception as e:
            print(f"获取代理 IP 出错: {e}")

    def phone_email_login(self, username, password, id_last_four, sms_code, max_retries=3):
        """实现12306官方账号的认证"""
        # 模拟登录请求
        login_url = "https://kyfw.12306.cn/otn/resources/login.html"  # 需确认实际登录接口
        data = {
            "username": username,
            "password": password
        }
        headers = {
            "User-Agent": get_random_user_agent(),
            "Referer": "https://kyfw.12306.cn/otn/resources/login.html",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Accept": "application/json, text/javascript, */*; q=0.01",
            "X-Requested-With": "XMLHttpRequest",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Accept-Encoding": "gzip, deflate, br"
        }
        for retry in range(max_retries):
            proxy = self.get_proxy()
            try:
                # 第一步：发送账号密码登录请求
                response = self.session.post(login_url, data=data, headers=headers, proxies=proxy, verify=False)
                response.encoding = 'utf-8'
                print(f"使用代理: {proxy}")
                print(f"服务器响应内容: {response.text}")

                if response.status_code == 200:
                    # 假设这里有获取短信验证码的接口
                    get_sms_code_url = "https://kyfw.12306.cn/passport/web/getMessageCode"  # 需替换为实际接口
                    sms_code_data = {
                        "id_last_four": id_last_four
                    }
                    sms_code_response = self.session.post(get_sms_code_url, data=sms_code_data, headers=headers, proxies=proxy, verify=False)
                    if sms_code_response.status_code == 200:
                        # 假设这里有提交验证码的接口
                        submit_sms_code_url = "https://kyfw.12306.cn/passport/web/getMessageCode"  # 需替换为实际接口
                        submit_data = {
                            "id_last_four": id_last_four,
                            "sms_code": sms_code
                        }
                        submit_response = self.session.post(submit_sms_code_url, data=submit_data, headers=headers, proxies=proxy, verify=False)
                        if submit_response.status_code == 200:
                            try:
                                result = submit_response.json()
                                if result.get("result_code") == 0:
                                    self.login_status = True
                                    self.login_time = time.time()
                                    print("登录成功")
                                    return True
                                else:
                                    print("登录失败，服务器返回错误结果")
                            except ValueError:
                                print("服务器返回的不是有效的 JSON 数据")
                else:
                    print(f"登录请求失败，状态码: {response.status_code}")
            except Exception as e:
                print(f"登录请求出错: {e}")

            print(f"重试次数: {retry + 1}/{max_retries}")
            time.sleep(2)  # 等待 2 秒后重试

        return False
    def send_sms_code(self, id_last_four):
        """发送短信验证码"""
        get_sms_code_url = "https://kyfw.12306.cn/passport/web/getMessageCode"  # 需替换为实际接口
        headers = {
            "User-Agent": get_random_user_agent(),
            "Referer": "https://kyfw.12306.cn/otn/resources/login.html",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Accept": "application/json, text/javascript, */*; q=0.01",
            "X-Requested-With": "XMLHttpRequest",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Accept-Encoding": "gzip, deflate, br"
        }
        proxy = self.get_proxy()
        try:
            sms_code_data = {
                "id_last_four": id_last_four
            }
            response = self.session.post(get_sms_code_url, data=sms_code_data, headers=headers, proxies=proxy, verify=False)
            response.encoding = 'utf-8'
            print(f"使用代理: {proxy}")
            print(f"服务器响应内容: {response.text}")

            if response.status_code == 200:
                try:
                    result = response.json()
                    if result.get("result_code") == 0:
                        return True
                except ValueError:
                    print("服务器返回的不是有效的 JSON 数据")
        except Exception as e:
            print(f"发送短信验证码出错: {e}")
        return False

    def captcha_recognition(self, captcha_image_path):
        """集成OCR/机器学习模型处理图形验证码"""
        try:
            image = Image.open(captcha_image_path)
            captcha_text = pytesseract.image_to_string(image)
            print(f"识别的验证码为: {captcha_text}")
            return captcha_text
        except Exception as e:
            print(f"验证码识别出错: {e}")
            return None

    def session_keep(self):
        """维持登录状态至少2小时"""
        if self.login_status:
            current_time = time.time()
            if current_time - self.login_time < 7200:
                print("会话仍在有效期内")
            else:
                print("会话已过期，请重新登录")
                self.login_status = False
        else:
            print("请先登录")